/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：实现MonoBehaviour单例模板
* CreateTime：2020-04-05 19:29:23
* Version：1.0
* Modify Recorder：
*************************************************/

using UnityEngine;

namespace TinyToolKit
{
    /// <summary>
    /// MonoBehaviour 单例的模板
    /// </summary>
    /// <typeparam name="T">需要实现单例的类</typeparam>
    public class TMonoSingleton<T> : MonoBehaviour where T : TMonoSingleton<T>
    {
        protected static T instance;

        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    string instanceName = typeof(T).Name;
                    T[] instances = FindObjectsOfType<T>();

                    if (instances.Length > 1)
                    {
                        instance = instances[0];

                        for (int i = 1; i < instances.Length; i++)
                        {
                            Destroy(instances[i].gameObject);
                        }

                        TLogTool.Error("{0}在场景中存在{1}个，返回第一个实例,销毁其他实例", instanceName,instances.Length);
                    }
                    else
                    {
                        if (instances.Length == 0)
                        {
                            TLogTool.Info("在场景中新增实例: " + instanceName);
                            
                            GameObject instanceObj = GameObject.Find(instanceName);
                            if (instanceObj == null)
                                instanceObj = new GameObject(instanceName);
                            instance = instanceObj.AddComponent<T>();
                        }
                        else
                        {
                            instance = instances[0];
                        }
                    }
                }
                return instance;
            }
        }

        protected virtual void OnDestroy()
		{
            instance = null;
		}
	}
}

